import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { fetchHomeDataAPI } from "@/api/homeAPI";
import type { ActionReducerMapBuilder, AsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import type { HomeData } from "@/type/HomeType";
import type { AsyncThunkConfig } from "@reduxjs/toolkit/dist/createAsyncThunk";


type InitialState = {
   homeData: HomeData
}

const initialState: InitialState = {
   homeData: {} as HomeData,
};

/**
 * @description 获取首页全部数据的asyncThunk函数
 * */
export const fetchHomeDataThunk: AsyncThunk<HomeData, string, AsyncThunkConfig> = createAsyncThunk("fetchHomeDataThunk", async (pageId, { rejectWithValue }) => {
   try {
      const { data } = await fetchHomeDataAPI(pageId);
      return data;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});


const homeStore = createSlice({
   name: "homeStore",
   initialState,
   reducers: {},
   extraReducers(builder: ActionReducerMapBuilder<InitialState>) {
      builder.addCase(fetchHomeDataThunk.fulfilled, (state: InitialState, action: PayloadAction<HomeData>): void => {
         state.homeData = action.payload;
      });
   },

});


export default homeStore.reducer;
